package com.jsp.study.db.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsp.study.db.Book;

@WebServlet("/findServlet")
public class FindServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public FindServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://118.89.160.58:3306/xbin_db?relaxAutoCommit=true&useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&failOverReadOnly=false";
			conn = DriverManager.getConnection(url, "xbin", "xbin0629");
			String sql = "select * from tb_books";
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			List<Book> bookList = new ArrayList<>();
			while(rs.next()) {
				Book book = new Book();
				book.setId(rs.getInt("id"));
				book.setName(rs.getString("name"));
				book.setPrice(rs.getDouble("price"));
				book.setBookCount(rs.getInt("bookcount"));
				book.setAuthor(rs.getString("author"));
				bookList.add(book);
			}
			request.setAttribute("bookList", bookList);
			rs.close();
			stmt.close();
			conn.close();
		} catch (Exception e) {
			System.out.println("操作数据库过程中出现异常");
		}
		request.getRequestDispatcher("db/bk_list.jsp").forward(request, response);  // 请求转发到bk_list.jsp
	}

}
